package com.ruge.test.springMVC.监听器;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;

/**
 * 创建人 ：爱丽丝、如歌
 * 创建时间 ：2018-07-01  10:04
 * 描述 ：在线人员的ip的获取
 */
@WebListener
public class OnLineDetail implements ServletRequestListener {

    private ArrayList<UserDetail> UserDetails;

    public void requestDestroyed(ServletRequestEvent sre) {


    }

    public void requestInitialized(ServletRequestEvent sre) {

        UserDetails = (ArrayList<UserDetail>) sre.getServletContext().getAttribute("UserDetail");

            if(UserDetails==null){
                    UserDetails = new ArrayList<UserDetail>();
            }

        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        String SessionId = request.getSession().getId();
        if(SessionUtil.getUserBySessionId(UserDetails, SessionId) != null){
            UserDetail userDetil = new UserDetail();
            userDetil.setSessionId(SessionId);
            userDetil.setFirstTime(LocalDateTime.now().toString().format("YYYY MM DD"));
            userDetil.setIP(request.getRemoteAddr());
            UserDetails.add(userDetil);
        }
        sre.getServletContext().setAttribute("UserDetails",UserDetails);
    }




}
